//
//  SchoolProfileViewController.m
//  Edumap
//
//  Created by 辰领科技 on 16/7/25.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "SchoolProfileViewController.h"
#import "SubjectsTableViewCell.h"
#import "UMSocial.h"
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "NavPointAnnotation.h"
#import "SharePopView.h"

static NSString *CellIdentifier = @"SubjectsTableViewCell";

@interface SchoolProfileViewController ()
<UITableViewDelegate,UITableViewDataSource,BestScrollViewDelegate,BestScrollViewDatasource,UIWebViewDelegate>

@property (weak, nonatomic) IBOutlet UIButton *collectionButton;
@property (weak, nonatomic) IBOutlet UILabel *schoolName;
@property (strong, nonatomic) IBOutlet UIScrollView *scroview;
@property (strong, nonatomic) IBOutlet UIView *slideButtonView;
@property (strong, nonatomic) IBOutlet UIButton *buttonOne;
@property (strong, nonatomic) IBOutlet UIButton *buttonTwo;
@property (strong, nonatomic) IBOutlet UIButton *buttonThree;
@property (strong, nonatomic) IBOutlet UIButton *buttonFour;
@property (strong, nonatomic) IBOutlet UIView *slideView;
@property (strong, nonatomic) IBOutlet UIWebView *webView;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (nonatomic,strong)  BestScrollView *headerScroll;//滚动栏
@property (nonatomic,strong)  NSMutableArray  *imageArray;


@property (strong, nonatomic) IBOutlet UIButton *BGbutton;
@property (strong, nonatomic) IBOutlet UIView *collectionView;//收藏View
@property (strong, nonatomic) IBOutlet UILabel *collectionLabel;

@property (strong, nonatomic) IBOutlet UIButton *collectionBack;

@property(nonatomic,assign)CGFloat lat;
@property(nonatomic,assign)CGFloat lng;

@end

@implementation SchoolProfileViewController

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //状态栏文字颜色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [self clearMapView];
    _imageArray = [NSMutableArray array];
    _headerScroll.datasource = nil;
    _headerScroll.delegate = nil;
    [_headerScroll removeFromSuperview];
    _backBlock();
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _imageArray = [NSMutableArray array];
    [self initViewLayout];
    [self getSchoolDetail];
    [self initNavgationMap];
}

#pragma mark  地图导航实例化--=========================================
- (void)initNavgationMap{
    [self initMapView];
    
    [self initNaviManager];
    
    [self initIFlySpeech];
    //导航控制器
    [self initNaviViewController];
    
    [self configMapView];
    
}
- (void)configMapView
{
    self.mapView.delegate = self;
    self.mapView.showsCompass= NO;
    self.mapView.showsScale = NO;
    self.mapView.showsUserLocation = YES;
}


- (void)initViewLayout {
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.scroview];
    [self adaptiveViewLayout:self.slideButtonView];
    [self adaptiveViewLayout:self.collectionView];
    self.collectionView.layer.cornerRadius = 5*VerticalRatio();
    self.collectionBack.layer.cornerRadius = 5*VerticalRatio();
    
    _scroview.showsVerticalScrollIndicator = FALSE;
    [self.tableView registerNib:[UINib nibWithNibName:CellIdentifier bundle:nil] forCellReuseIdentifier:CellIdentifier];
//    self.tableView.delegate = self;
//    self.tableView.dataSource = self;
//    self.tableView.hidden = YES;
    
    //广告栏
    _headerScroll=[[BestScrollView alloc]  initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 177), NO)];
    [self.scroview insertSubview:_headerScroll belowSubview:_schoolName];
    
    NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@%@%@",IP_Address_Fresh,JY_queryMsdeContent,_schoolId]]];
    [_webView loadRequest:req];
    _webView.backgroundColor = [UIColor whiteColor];
    _webView.delegate = self;
    
 
}

#pragma mark - UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    
    CGRect newFrame = _webView.frame;
    newFrame.size.height = 1;
    _webView.frame = newFrame;
    CGFloat webViewHeight=[_webView.scrollView contentSize].height;
    newFrame.size.height = webViewHeight;
    _webView.frame = newFrame;
    
    _scroview.contentSize = CGSizeMake(0, (357*VerticalRatio())+_webView.frame.size.height+(20*VerticalRatio()));
    if (_scroview.contentSize.height <= 568*VerticalRatio()) {
        _scroview.contentSize = CGSizeMake(0, 569*VerticalRatio());
    }
}
- (IBAction)back:(id)sender {
    [self backBtn];
    
}
#pragma mark - 取消收藏 && 取消分享
- (IBAction)cancel:(id)sender {
    _BGbutton.hidden = YES;
    _collectionView.hidden = YES;
}


#pragma mark - 分享
- (IBAction)share:(id)sender {
    SharePopView * popView = [[SharePopView alloc]initWithTitles:@[@"微信好友",@"朋友圈",@"QQ空间",@"QQ好友"] complect:^(NSInteger index) {
        if (index == 0) {
            //微信好友
            [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatSession] content:_nameLabel.text image:[UIImage imageNamed:@"58.png"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
                if (response.responseCode == UMSResponseCodeSuccess) {
                    //            NSLog(@"分享成功！");
                }
            }];
            
        } else if (index == 1) {
            //朋友圈
            [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatTimeline] content:_nameLabel.text image:[UIImage imageNamed:@"58.png"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
                if (response.responseCode == UMSResponseCodeSuccess) {
                    //            NSLog(@"分享成功！");
                }
            }];
            
            
        } else if (index == 2) {
            //QQ空间
            [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToQzone] content:_nameLabel.text image:[UIImage imageNamed:@"58.png"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
                if (response.responseCode == UMSResponseCodeSuccess) {
                    //            NSLog(@"分享成功！");
                }
            }];
            
        } else if (index == 3) {
            //QQ好友
            [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToQQ] content:_nameLabel.text image:[UIImage imageNamed:@"58.png"] location:nil urlResource:nil presentedController:self completion:^(UMSocialResponseEntity *response){
                if (response.responseCode == UMSResponseCodeSuccess) {
                    //            NSLog(@"分享成功！");
                }
            }];
        }
        
    }];
    [popView show];
}

#pragma mark - 收藏
- (IBAction)collection:(id)sender {
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return;
    }
    if (self.collectionButton.selected) {
        NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
        [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
        [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
        [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
        [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
        [dic setObject:_schoolId forKey:@"msdeId"];
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:JY_canleCollectMallStoreDeveloper withHttpType:@"POST" withTag:JY_JY_canleCollectMallStoreDeveloper];
    } else if (!self.collectionButton.selected) {
        NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
        [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
        [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
        [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
        [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
        [dic setObject:self.schoolId forKey:@"msdeId"];
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:JY_collectMallStoreDeveloper withHttpType:@"POST" withTag:JY_JY_collectMallStoreDeveloper];
    }

}

#pragma mark - 学校简介 && 荣誉资质 && 招生信息 && 教授科目
- (IBAction)button:(UIButton *)sender {
//    _webView = [[UIWebView alloc]init];
    if (sender == _buttonOne) {
        _buttonOne.selected = YES;
        _buttonTwo.selected = NO;
        _buttonThree.selected = NO;
        _buttonFour.selected = NO;
        [UIView animateWithDuration:0.2 animations:^{
            _slideView.frame = flexibleFrame(CGRectMake(18, 41, 44, 1), YES);
        }];
        
            NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@%@%@",IP_Address_Fresh,JY_queryMsdeContent,_schoolId]]];
            [_webView loadRequest:req];

    } else if (sender == _buttonTwo) {
        
        _buttonOne.selected = NO;
        _buttonTwo.selected = YES;
        _buttonThree.selected = NO;
        _buttonFour.selected = NO;
        [UIView animateWithDuration:0.2 animations:^{
            _slideView.frame = flexibleFrame(CGRectMake(98, 41, 44, 1), YES);
        }];
        NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@%@%@",IP_Address_Fresh,JY_queryMsdeHonor,_schoolId]]];
        [_webView loadRequest:req];
        
    } else if (sender == _buttonThree) {
        
        _buttonOne.selected = NO;
        _buttonTwo.selected = NO;
        _buttonThree.selected = YES;
        _buttonFour.selected = NO;
        [UIView animateWithDuration:0.2 animations:^{
            _slideView.frame = flexibleFrame(CGRectMake(178, 41, 44, 1), YES);
        }];
        NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@%@%@",IP_Address_Fresh,JY_queryMsdeEnroll,_schoolId]]];
        [_webView loadRequest:req];
        
    } else if (sender == _buttonFour) {
        
        _buttonOne.selected = NO;
        _buttonTwo.selected = NO;
        _buttonThree.selected = NO;
        _buttonFour.selected = YES;
        [UIView animateWithDuration:0.2 animations:^{
            _slideView.frame = flexibleFrame(CGRectMake(258, 41, 44, 1), YES);
        }];
        NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://%@%@%@",IP_Address_Fresh,JY_queryMsdeSubject,_schoolId]]];
        [_webView loadRequest:req];
        
    }

}


#pragma mark   ===== 电话
- (IBAction)callHandel:(id)sender {
    [Common callPhone:_phoneLabel.text view:self.view];
}

#pragma mark   ===== 地图导航
- (IBAction)navHandel:(id)sender {
    NSArray *endPoints;
    NavPointAnnotation * endAnnotation = [[NavPointAnnotation alloc] init];
    CLLocationCoordinate2D coordinate1 = CLLocationCoordinate2DMake(_lat,_lng);
    [endAnnotation setCoordinate:coordinate1];
    endPoints = @[[AMapNaviPoint locationWithLatitude:endAnnotation.coordinate.latitude
                                            longitude:endAnnotation.coordinate.longitude]];
    [self.naviManager calculateDriveRouteWithEndPoints:endPoints
                                             wayPoints:nil
                                       drivingStrategy:0];

}


#pragma mark === 学校详情
- (void)getSchoolDetail{
   
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    if ([Common getLoginStatus]) {
        [dic setObject:[Common getLoginInfo][Key_User_userId] forKey:@"museId"];
    }
    [dic setObject:_schoolId forKey:@"msdeId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:JY_mallStoreDeveloperDetails withHttpType:@"POST" withTag:JY_JY_mallStoreDeveloperDetails];
    
}



#pragma mark - <UITableViewDelegate&&UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 78*VerticalRatio();
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SubjectsTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell= [[SubjectsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    
    
    return cell;
}

//定义 UITableView cell 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}


#pragma  mark BestView Delegate Data=source=====================


- (NSInteger)numberOfPages
{
    
    return  self.imageArray.count;
    
}

- (UIView *)pageAtIndex:(NSInteger)index
{
    
    if (self.imageArray.count>0) {
        
        UIImageView  *imageView=[[UIImageView alloc]  initWithFrame: flexibleFrame(CGRectMake(0, 0, 320, 177), NO)];
        [imageView  sd_setImageWithURL:[NSURL URLWithString: [NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,_imageArray[index]]] placeholderImage:[UIImage imageNamed:@"school5"]];
        return imageView;
    }
    return nil;
}


- (void)didClickPage:(BestScrollView *)csView atIndex:(NSInteger)index
{
}




#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    if (tag==JY_JY_mallStoreDeveloperDetails) {
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            NSDictionary * dic = database[@"result"];
            
            _lat = [dic[@"msdeLat"] floatValue];
            _lng = [dic[@"msdeLng"] floatValue];
            _schoolName.text = [NSString stringWithFormat:@"%@",dic[@"msdeName"]];
            _nameLabel.text = [NSString stringWithFormat:@"%@",dic[@"msdeAddress"]];
            _timeLabel.text = [NSString stringWithFormat:@"报名时间%@",dic[@"msdeRegistTime"]];
            _phoneLabel.text = [NSString stringWithFormat:@"%@",dic[@"msdePhone"]];
            NSString * collect = [NSString stringWithFormat:@"%@",dic[@"isCollect"]];
            if ([collect isEqualToString:@"1"]) {
                _collectionButton.selected = YES;
            }else{
                _collectionButton.selected = NO;
            }
            
            NSString * images = [NSString stringWithFormat:@"%@",dic[@"msdeMultiImage"]];
            if (images.length>1) {
                images = [images substringToIndex:images.length-1];

            }
              self.imageArray = [[images componentsSeparatedByString:@","]mutableCopy];
//            NSArray *imageArr = [images componentsSeparatedByString:@","];
//            for (NSString *img in imageArr) {
//                [self.imageArray addObject:img];
//            }
            self.headerScroll.delegate=self;
            self.headerScroll.datasource=self;
            [self.headerScroll showImageArray:self.imageArray   withAnimation:YES];

        }
    }else if (tag == JY_JY_collectMallStoreDeveloper){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else {
            self.collectionLabel.text = @"收藏成功";
            _collectionView.hidden = NO;
            _BGbutton.hidden = NO;
            _collectionButton.selected = YES;
        }
    
    }else if (tag == JY_JY_canleCollectMallStoreDeveloper){
            if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
                
                [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
                
            }else {
                self.collectionLabel.text = @"取消收藏";
                _collectionView.hidden = NO;
                _BGbutton.hidden = NO;
                _collectionButton.selected = NO;
 
            }
        }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
}

@end
